import { defineStore } from "pinia";
import { userState } from "@/store/types/types.ts";
import { loginResponseData } from "@/api/user/type.ts";
import { reqLogin } from "@/api/user";
import { LoginForm } from "@/api";
import { SET_TOKEN } from "@/utils/token.ts";

const useUserStore = defineStore("User", {
  state: (): userState => {
    return {
      token: "",
      username: "",
      avatar: "",
    };
  },
  actions: {
    //用户登录的方法
    async userLogin(data: LoginForm) {
      //登录请求
      const result: loginResponseData = await reqLogin(data);

      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code == 200) {
        //pinia仓库存储一下token
        this.token = result.data as string;
        // token 存入本地
        SET_TOKEN(this.token);
        console.log("存了" + this.token);
        //能保证当前async函数返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(result.data);
      }
    },
  },
});

export default useUserStore;
